package com.wyj.wuliwuli.shiro;

import com.wyj.wuliwuli.entity.WuliUser;
import com.wyj.wuliwuli.entity.mapper.WuliUserMapper;
import com.wyj.wuliwuli.service.WuliUserService;
import com.wyj.wuliwuli.utils.JWTUtil;
import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CommonRealm extends AuthorizingRealm {

    @Autowired
    private WuliUserMapper wuliUsersMapper;
    @Autowired
    private WuliUserService wuliUserService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 授权
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String key = JWTUtil.getKey(principals.toString());
        WuliUser wuliUser = wuliUserService.getByUsername(key);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getKey(token);
        if (username == null) {
            throw new AuthenticationException("token invalid");
        }
        WuliUser wuliUser = wuliUserService.getByUsername(username);
        if (wuliUser == null) {
            throw new AuthenticationException("User didn't existed!");
        }
        if (!JWTUtil.verifyToken(token, wuliUser.getUsername())) {
            throw new AuthenticationException("Username or password error");
        }
        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }

}
